package com.ysh.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * 袁胜虎 on 2022/9/25 17:38
 */
public class MyByatisUtils {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static  SqlSession openSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }
    public static  void commit(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null){
            sqlSession.commit();
        }
    }
    public static void rllback(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null ){
            sqlSession.rollback();
        }
    }
    public static void close(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null){
            sqlSession.close();
            threadLocal.remove();
        }
    }
    public static <T>T getMapper(Class<T>clazz){
        SqlSession sqlSession = threadLocal.get();
        //没有的情况下创建
        if (sqlSession == null){
            sqlSession = openSession();
        }
        //返回mapper
        return  sqlSession.getMapper(clazz);
    }
}
